# -*- coding: utf-8 -*-
import json
import os
import traceback

from common.db import MySql
from config.config import Config
from common.log import logger


class Utils:

    @staticmethod
    def get_case_data(file_name, case_name=None):
        """
        根据项目名称，环境读取对应data目录下的测试数据
        :param case_name: 测试数据名
        :param file_name: 测试数据文件名，XX.json
        :return:
        """
        env = Config().env
        project_name = Config().project_name
        data_path_dir = str(
            os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'data', project_name, env, file_name)))
        test_data = Config().get_config(data_path_dir, case_name)
        return test_data

    # 获取测试图片数据
    @staticmethod
    def get_test_pic(pic_name):
        env = Config().env
        path = os.path.abspath(
            os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))))
        pic_path = path + f'/data/image/{env}/{pic_name}'
        return pic_path

    # 获取网上开户视频测试数据
    @staticmethod
    def get_wskh_video(video_name):
        path = os.path.abspath(
            os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))))
        pic_path = path + f'/data/wskh_video/{video_name}'
        return pic_path

    @staticmethod
    def get_sms_code():
        """
        获取短信验证码
        :return:
        """
        code = Config().data['execute']['code']
        return code

    @staticmethod
    def search_client(msg):
        """
        大字段表检查，资金号查询，不足12位前面自动补0
        :param msg: 资金号/客户号
        :return:
        """
        path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'sql/service_sql.json'))
        data = Config().get_config(path_dir)
        clinet_id = str(msg).rjust(12, "0")
        sql = data['search_client'].replace("##", str(clinet_id))
        result = json.loads(MySql("mysql").execute(sql).values[0][0])
        s = traceback.extract_stack()
        m = {'appname': s[-2].filename.split('\\')[-1] + f' line in {s[-2].lineno}'}
        logger.info('大字段表检查', extra=m)
        return result

    @staticmethod
    def search_for_param(engine, sql_path, sql_key, msg, log_info=""):
        """
        多个参数查询，sql中参数用##表示，msg依次替换##
        :param log_info: 日志信息
        :param engine: 数据库连接信息
        :param sql_path: 需要执行的sql.json文件路劲，以项目顶层为基准，eg:sql/service_sql.json
        :param sql_key: sql文件对应的dict的key
        :param msg: 需要查询的字段的值 list
        :return:
        """
        path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, sql_path))
        data = Config().get_config(path_dir)
        sql = data[sql_key]
        sql_new = None
        s = traceback.extract_stack()
        m = {'appname': s[-2].filename.split('\\')[-1] + f' line in {s[-2].lineno}'}
        if isinstance(msg, list):
            for i in msg:
                sql_new = sql.replace("##", str(i), 1)
                sql = sql_new
            result = MySql(engine).execute(sql_new)
            logger.info(f'{log_info}', extra=m)
            return result
        else:
            logger.info("msg格式错误，应为list", extra=m)

    @staticmethod
    def execute_sql(engine, sql_path, sql_key, log_info=""):
        """
        执行sql语句
        :param log_info:  日志信息
        :param engine: 数据库连接信息
        :param sql_path: 需要执行的sql.json文件路劲，以项目顶层为基准，eg:sql/service_sql.json
        :param sql_key:需要执行的sql.json文件中的key,eg: all
        :return:
        """
        path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, sql_path))
        data = Config().get_config(path_dir)
        sql = data[sql_key]
        result = MySql(engine).execute(sql)
        s = traceback.extract_stack()
        m = {'appname': s[-2].filename.split('\\')[-1] + f' line in {s[-2].lineno}'}
        logger.info(f'{log_info}', extra=m)
        return result

    @staticmethod
    def check_val(exp_val, act_val, field):
        if exp_val not in act_val:
            logger.info(field + '的结果不一致，期望结果是' + exp_val + '而实际结果是' + act_val + '。', extra={"appname": "checkVal"})
        else:
            logger.info(field + '的期望结果' + exp_val + '与实际结果一致。', extra={"appname": "checkVal"})


if __name__ == '__main__':
    # Utils.search_for_param('uf', 'sql/service_sql.json', 'initial_uf_sql_dormancy_FUNDACCOUNT', ['C','000100183083'],
    #                        '设置休眠户。')
    # Utils.search_for_param('uf', 'sql/service_sql.json', 'initial_uf_sql_dormancy_STOCKHOLDER', ['C','000100183083'],
    #                        '设置休眠户。')

    Utils.search_for_param('bop', 'sql/my_sql.json', 'init_bop', ['002046000026'],
                           '重置bop业务。')
    Utils.search_for_param('mysql', 'sql/my_sql.json', 'init_zhong_tai', ['002046000026'],
                           '重置新中台业务。')
